<template>
	<view class="uni-calendar">
		<view v-if="!insert&&show" class="uni-calendar__mask" :class="{'uni-calendar--mask-show':aniMaskShow}" @click="clean"></view>
		<view v-if="insert || show" class="uni-calendar__content r8" :class="{'uni-calendar--fixed':!insert,'uni-calendar--ani-show':aniMaskShow}">
			<view v-if="range" class="flex flexC borb pt10 pb6">
				<!-- <text class="uni-calendar__backtoday" @click="backtoday">回到今天</text> -->
				<view class="flex1 aliC"><text @click="backdays(0,1)" class="uni-calendar__backtoday" :class="dayIndex==1?'active':''">今天</text></view>
				<view class="flex1 aliC"><text @click="backdays(-6,2)" class="uni-calendar__backtoday" :class="dayIndex==2?'active':''">近7天</text></view>
				<view class="flex1 aliC"><text @click="backdays(-29,3)" class="uni-calendar__backtoday" :class="dayIndex==3?'active':''">近30天</text></view>
				<view class="flex1 aliC"><text @click="backmonth(4)" class="uni-calendar__backtoday" :class="dayIndex==4?'active':''">本月</text></view>
			</view>
			<view v-if="range" class="flex flexB flexC pt18 mb12">
				<view class="flex1 pl20 pr10 c33">
					<view class="c99 fs14">开始时间</view>
					<view class="mt4">
						<text class="fs15 mr4" :class="!cale.multipleStatus.before?'c99':''">{{getDateTime(cale.multipleStatus.before)||'请选择日期'}}</text>
						<text class="fs12">{{getweekday(cale.multipleStatus.before)}}</text>
					</view>
				</view>
				<text class="hr"></text>
				<view class="flex1 pl30">
					<view class="fs14 c99">结束时间</view>
					<view class="mt4">
						<text class="fs15 mr4" :class="!cale.multipleStatus.after?'c99':''">{{getDateTime(cale.multipleStatus.after)||'请选择日期'}}</text>
						<text class="fs12">{{getweekday(cale.multipleStatus.after)}}</text>
					</view>
				</view>
			</view>
			<view class="uni-calendar__header flexB">
				<view class="uni-calendar__header-btn-box" @click.stop="pre">
					<text class="arrows icon-jiantou1 fs20 c99"></text>
				</view>
				<!-- <picker mode="date" :value="date" fields="month" @change="bindDateChange"> -->
					<text class="uni-calendar__header-text">{{ (nowDate.year||'') +'年'+( nowDate.month||'') +'月'}}</text>
				<!-- </picker> -->
				<view class="uni-calendar__header-btn-box" @click.stop="next">
					<text class="arrows icon-jiantou fs20 c99"></text>
				</view>
			</view>
			<view class="uni-calendar__box px16">
				<view v-if="showMonth" class="uni-calendar__box-bg">
					<text class="uni-calendar__box-bg-text">{{nowDate.month}}</text>
				</view>
				<view class="uni-calendar__weeks">
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text ceb">日</text>
					</view>
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text">一</text>
					</view>
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text">二</text>
					</view>
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text">三</text>
					</view>
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text">四</text>
					</view>
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text">五</text>
					</view>
					<view class="uni-calendar__weeks-day">
						<text class="uni-calendar__weeks-day-text ceb">六</text>
					</view>
				</view>
				<view class="uni-calendar__weeks" v-for="(item,weekIndex) in weeks" :key="weekIndex">
					<view class="uni-calendar__weeks-item" v-for="(weeks,weeksIndex) in item" :key="weeksIndex">
						<calendar-item :weeks="weeks" :calendar="calendar" :selected="selected" :lunar="lunar" @change="choiceDate"></calendar-item>
					</view>
				</view>
			</view>
			<view v-if="!insert" class="uni-calendar__header uni-calendar--fixed-top">
				<view class="uni-calendar__header-btn-box flex1 line" @click="close">
					<text class="uni-calendar__header-text uni-calendar--fixed-width ceb">取消</text>
				</view>
				<view class="uni-calendar__header-btn-box flex1" @click="confirm">
					<text class="uni-calendar__header-text uni-calendar--fixed-width ceb">确定</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Calendar from './util.js';
	import calendarItem from './uni-calendar-item.vue'
	/**
	 * Calendar 日历
	 * @description 日历组件可以查看日期，选择任意范围内的日期，打点操作。常用场景如：酒店日期预订、火车机票选择购买日期、上下班打卡等
	 * @tutorial https://ext.dcloud.net.cn/plugin?id=56
	 * @property {String} date 自定义当前时间，默认为今天
	 * @property {Boolean} lunar 显示农历
	 * @property {String} startDate 日期选择范围-开始日期
	 * @property {String} endDate 日期选择范围-结束日期
	 * @property {Boolean} range 范围选择
	 * @property {Boolean} insert = [true|false] 插入模式,默认为false
	 * 	@value true 弹窗模式
	 * 	@value false 插入模式
	 * @property {Boolean} clearDate = [true|false] 弹窗模式是否清空上次选择内容
	 * @property {Array} selected 打点，期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}]
	 * @property {Boolean} showMonth 是否选择月份为背景
	 * @event {Function} change 日期改变，`insert :ture` 时生效
	 * @event {Function} confirm 确认选择`insert :false` 时生效
	 * @event {Function} monthSwitch 切换月份时触发
	 * @example <uni-calendar :insert="true":lunar="true" :start-date="'2019-3-2'":end-date="'2019-5-20'"@change="change" />
	 */
	export default {
		components: {
			calendarItem
		},
		props: {
			date: {
				type: String,
				default: ''
			},
			selected: {
				type: Array,
				default () {
					return []
				}
			},
			lunar: {
				type: Boolean,
				default: false
			},
			startDate: {
				type: String,
				default: ''
			},
			endDate: {
				type: String,
				default: ''
			},
			range: {
				type: Boolean,
				default: true
			},
			insert: {
				type: Boolean,
				default: false
			},
			showMonth: {
				type: Boolean,
				default: false
			},
			clearDate: {
				type: Boolean,
				default: true
			},
			defaultStartDate: { //默认选中开始日期范围
				type: String,
				default: ''
			},
			defaultEndDate: { //默认选中结束日期范围
				type: String,
				default: ''
			},
		},
		data() {
			return {
				show: false,
				weeks: [],
				calendar: {},
				nowDate: '',
				aniMaskShow: false,
				dayIndex: -1
			}
		},
		watch: {
			date(newVal) {
				this.cale.setDate(newVal)
				this.init(this.cale.selectDate.fullDate)
			},
			startDate(val){
				this.cale.resetSatrtDate(val)
			},
			endDate(val){
				this.cale.resetEndDate(val)
			},
			selected(newVal) {
				this.cale.setSelectInfo(this.nowDate.fullDate, newVal)
				this.weeks = this.cale.weeks
			}
		},
		created() {
			// 获取日历方法实例
			this.cale = new Calendar({
				// date: new Date(),
				selected: this.selected,
				startDate: this.startDate,
				endDate: this.endDate,
				range: this.range,
				defaultStartDate: this.defaultStartDate,
				defaultEndDate: this.defaultEndDate
			})
			// 选中某一天
			this.cale.setDate(this.date)
			this.init(this.cale.selectDate.fullDate)
			// this.setDay
		},
		methods: {
			// 日期格式化星期几（星期一）
			getweekday(date){
				if(!date) return
				var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
				var week = weekArray[new Date(date).getDay()];
				return '星期'+week;
			},
			// 日期格式化月日（7月28日）
			getDateTime(date) {
				if(!date) return ''
				let d = new Date(date)
				let str = (d.getMonth() + 1) +"月"+ d.getDate() +"日"
				return str
			},
			// 获取指定最近多少天 num: -6 最近7天
			backdays(num,index) {
				this.dayIndex = index
				let date = this.getDay(num);
				let endDate = this.cale.getDate(new Date()).fullDate;
				this.cale.cleanMultipleStatus();
				this.cale.setMultiple(date);
				this.cale.setMultiple(endDate);
				this.cale.setDate(endDate); // 传入结束时间参数时当前页面显示的结束时间的月份（选择范围跨多个月时）
				this.init(endDate);
				this.weeks = this.cale.weeks;
			},
			// 获取本月日期范围
			backmonth(index) {
				this.dayIndex = index;
				let date = this.getDay(-(new Date().getDate())+1);
				let endDate = this.cale.getDate(new Date()).fullDate;
				this.cale.cleanMultipleStatus();
				this.cale.setMultiple(date);
				this.cale.setMultiple(endDate);
				this.cale.setDate(endDate)  // 传入结束时间参数时当前页面显示的结束时间的月份（选择范围跨多个月时）
				this.init(endDate);
				this.weeks = this.cale.weeks;
			},
			// 最近天数转化成日期格式 （最近7天：2021-07-21; 当前时间2021-07-28）
			getDay(num, str='-') {
			    var today = new Date();
			    var nowTime = today.getTime();
			    var ms = 24*3600*1000*num;
			    today.setTime(parseInt(nowTime+ ms));
			    var oYear = today.getFullYear();
			    var oMoth = (today.getMonth() + 1).toString();
			    if (oMoth.length <= 1) oMoth = '0' + oMoth;
			    var oDay = today.getDate().toString();
			    if (oDay.length <= 1) oDay = '0' + oDay;
			    return oYear + str + oMoth + str + oDay;
			},
			// 取消穿透
			clean() {},
			bindDateChange(e) {
				const value = e.detail.value + '-1';
				this.cale.setDate(value);
				this.init(value);
			},
			/**
			 * 初始化日期显示
			 * @param {Object} date
			 */
			init(date) {
				this.weeks = this.cale.weeks;
				this.nowDate = this.calendar = this.cale.getInfo(date);
			},
			/**
			 * 打开日历弹窗
			 */
			open() {
				// 弹窗模式并且清理数据
				if (this.clearDate && !this.insert) {
					this.cale.cleanMultipleStatus();
					if(this.defaultStartDate||this.defaultEndDate) { //父组件传入默认开始日期和结束日期时 选中指定日期范围
						this.dayIndex = -1;
						this.cale.setMultiple(this.defaultStartDate); //设置开始日期
						this.cale.setMultiple(this.defaultEndDate||this.defaultStartDate);  //设置结束日期（如果没有传入结束时间默认显示开始时间
						this.cale.setDate(this.defaultEndDate||this.defaultStartDate);
						this.init(this.defaultEndDate||this.defaultStartDate);
					}
				}
				this.show = true;
				this.weeks = this.cale.weeks;
				this.$nextTick(() => {
					setTimeout(() => {
						this.aniMaskShow = true
					}, 50)
				})
			},
			/**
			 * 关闭日历弹窗
			 */
			close() {
				this.aniMaskShow = false;
				this.$nextTick(() => {
					setTimeout(() => {
						this.show = false;
						this.$emit('close');
					}, 300)
				})
			},
			/**
			 * 确认按钮
			 */
			confirm() {
				this.setEmit('confirm');
				this.close();
			},
			/**
			 * 变化触发
			 */
			change() {
				if (!this.insert) return;
				this.setEmit('change');
			},
			/**
			 * 选择月份触发
			 */
			monthSwitch() {
				let {
					year,
					month
				} = this.nowDate
				this.$emit('monthSwitch', {
					year,
					month: Number(month)
				})
			},
			/**
			 * 派发事件
			 * @param {Object} name
			 */
			setEmit(name) {
				let {
					year,
					month,
					date,
					fullDate,
					lunar,
					extraInfo
				} = this.calendar
				this.$emit(name, {
					range: this.cale.multipleStatus,
					year,
					month,
					date,
					fulldate: fullDate,
					lunar,
					extraInfo: extraInfo || {}
				})
			},
			/**
			 * 选择天触发
			 * @param {Object} weeks
			 */
			choiceDate(weeks) {
				if (weeks.disable) return;
				this.dayIndex = -1;
				this.calendar = weeks;
				// 设置多选
				if(this.range) {
					this.cale.setMultiple(this.calendar.fullDate);
				}
				this.weeks = this.cale.weeks;
				this.change();
			},
			/**
			 * 回到今天
			 */
			backtoday() {
				console.log(this.cale.getDate(new Date()).fullDate);
				let date = this.cale.getDate(new Date()).fullDate
				this.cale.setDate(date)
				this.init(date)
				this.change()
			},
			/**
			 * 上个月
			 */
			pre() {
				const preDate = this.cale.getDate(this.nowDate.fullDate, -1, 'month').fullDate
				this.setDate(preDate)
				this.monthSwitch()

			},
			/**
			 * 下个月
			 */
			next() {
				const nextDate = this.cale.getDate(this.nowDate.fullDate, +1, 'month').fullDate
				this.setDate(nextDate)
				this.monthSwitch()
			},
			/**
			 * 设置日期
			 * @param {Object} date
			 */
			setDate(date) {
				this.cale.setDate(date)
				this.weeks = this.cale.weeks
				this.nowDate = this.cale.getInfo(date)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.arrows {width: 16upx;height: 16upx;
		&.icon-jiantou {transform: rotate(-45deg); border-right: 4upx solid #e5e5e5;border-bottom: 4upx solid #e5e5e5;}
		&.icon-jiantou1 {transform: rotate(45deg);border-left: 4upx solid #e5e5e5;border-bottom: 4upx solid #e5e5e5;}
	}
	.uni-calendar {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
	}

	.uni-calendar__mask {
		position: fixed;
		bottom: 0;
		top: 0;
		left: 0;
		right: 0;
		background-color: $uni-bg-color-mask;
		transition-property: opacity;
		transition-duration: 0.3s;
		opacity: 0;
		/* #ifndef APP-NVUE */
		z-index: 99;
		/* #endif */
	}

	.uni-calendar--mask-show {
		opacity: 1
	}

	.uni-calendar--fixed {
		position: fixed;
		top: 12%;
		left: 5%;
		width: 90%;
		transition-property: transform;
		transition-duration: 0.3s;
		transform: translateY(460px);
		/* #ifndef APP-NVUE */
		z-index: 99;
		/* #endif */
	}

	.uni-calendar--ani-show {
		transform: translateY(0);
	}

	.uni-calendar__content {
		background-color: #fff;
	}

	.uni-calendar__header {
		position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		height: 100upx;
	}

	.uni-calendar--fixed-top {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: space-between;
		border-top-color: $uni-border-color;
		border-top-style: solid;
		border-top-width: 1px;
	}

	.uni-calendar--fixed-width {
		width: 100upx;
		// padding: 0 15px;
	}

	.uni-calendar__backtoday {
		padding: 6upx 26upx; line-height: 80upx; font-size: 28upx; color: #666; box-sizing: border-box;
		&.active{
			color: $uni-color-primary;
			border: 1px solid $uni-color-primary;
			border-radius: 80upx;
			background-color: #f1f8fb;
		}
	}

	.uni-calendar__header-text {
		text-align: center;
		width: 200upx;
		font-size: 32upx;
		color: $uni-text-color;
		&.ceb {color: #00A3EB;}
	}

	.uni-calendar__header-btn-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: center;
		width: 100upx;
		height: 100upx;
		position: relative;
		&.line:after {content: '';width: 1px; height: 48upx;background-color: #EEEEEE;position: absolute; top: calc(50% - 24upx);right: 0;}
	}
	.uni-calendar__weeks {
		position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	.uni-calendar__weeks-item {
		flex: 1;
	}

	.uni-calendar__weeks-day {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 90upx;
		color: #999;
	}

	.uni-calendar__weeks-day-text {
		font-size: 28upx;
	}

	.uni-calendar__box {
		position: relative;
	}

	.uni-calendar__box-bg {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.uni-calendar__box-bg-text {
		font-size: 200px;
		font-weight: bold;
		color: $uni-text-color-grey;
		opacity: 0.1;
		text-align: center;
		/* #ifndef APP-NVUE */
		line-height: 1;
		/* #endif */
	}
</style>
